package com.book.flink

import com.alibaba.fastjson.JSON
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

object HttpClientJob {

  def main(args: Array[String]): Unit = {
    val postUrl = "http://web.books.com/books/api/web/index.php/streaming/kafka"
    val params ="""{"data":[{"one":1,"two":"这是2"}]}"""

    println(postResponse(postUrl, params, """{"Content-Type": "application/json"}"""))
  }

  def postResponse(url: String, params: String = null, header: String = null) : String = {
    val httpClient = HttpClients.createDefault()
    val post = new HttpPost(url)

    if (null != header) {
      val json = JSON.parseObject(header)
      json.keySet().toArray().map(_.toString).foreach(key => post.setHeader(key, json.getString(key)))
    }

    if (null != params) {
      post.setEntity(new StringEntity(params, "UTF-8"))
    }
    val response = httpClient.execute(post)
    EntityUtils.toString(response.getEntity, "UTF-8")
  }

}
